package com.sigmatrix.h5.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sigmatrix.h5.dao.DisDealerAcctDao;
import com.sigmatrix.h5.dao.EnterpriseDao;
import com.sigmatrix.h5.dto.LoginData;
import com.sigmatrix.h5.entity.DisDealerAcct;
import com.sigmatrix.h5.entity.Enterprise;
import com.sigmatrix.h5.enums.ResponseEnum;
import com.sigmatrix.h5.exception.DaoException;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.utils.Cons;
import com.sigmatrix.h5.utils.JacksonUtil;
import com.sigmatrix.h5.utils.MD5Utils;
import com.sigmatrix.h5.utils.Utils;
import com.sigmatrix.h5.web.args.LoginParam;

/**
 * 用于分销app。
 * 
 * 使用redis作为session存储介质
 * 
 * @author wei.wang
 *
 */
@Service
public class DisAppAuthenticator extends DefaultAuthenticator {
	private static Logger logger = LoggerFactory.getLogger(DisAppAuthenticator.class);
	
	@Autowired
	private transient EnterpriseDao enterpriseDao;
	
	@Autowired
	private DisDealerAcctDao disDealerAcctDao;
	
	@Override
	public AuthenticationInfo authenticate(LoginParam param) {
		
		AuthenticationInfo info = new AuthenticationInfo();
			DisDealerAcct dealerAcct;
			try {
				dealerAcct = disDealerAcctDao.findByAcct(null, param.getLoginName());
			} catch (DaoException e) {
				throw new MessageException(String.valueOf(ResponseEnum.EXCEPTION.getCode()),"系统异常");
			}
			if(Utils.isEmpty(dealerAcct)){
				throw new MessageException(String.valueOf(ResponseEnum.NO_DATA.getCode()),"账号不存在");
			}
			//判断状态是否为启用
			if(Cons.STATUS_ENABLE != dealerAcct.getStatus()){
				throw new MessageException(String.valueOf(ResponseEnum.EXCEPTION.getCode()),"账号不可用");
			}
		    //账号类型, 1-企业CRM账号,2-经销商CRM账号,3-终端门店CRM账号
			if(Cons.ACCT_TYPE_DEALER != dealerAcct.getAcctType()){
				throw new MessageException(String.valueOf(ResponseEnum.EXCEPTION.getCode()),"请使用经销商CRM账号");
			}
			//密码加密验证是否正确
			final String pwd = MD5Utils.getMD5Code(param.getLoginPwd());
			if(!pwd.equals(dealerAcct.getPwd())){
				throw new MessageException(String.valueOf(ResponseEnum.EXCEPTION.getCode()),"密码不正确");
			}
			
			//查询账号所属企业信息
			Enterprise enterprise = null;//企业信息
			final Integer eseId = dealerAcct.getEnterpriseId();//企业id
			if(Utils.isNotEmpty(eseId)){
				enterprise = enterpriseDao.findById(eseId);
			}
			if(Utils.isEmpty(enterprise)||Utils.isEmpty(enterprise.getCode())){
				throw new MessageException(String.valueOf(ResponseEnum.EXCEPTION.getCode()),"账号企业信息不存在");
			}
			
			info.setLoginType(param.getLoginType());
			info.setAcctId(dealerAcct.getId());
			info.setLoginName(param.getLoginName());
			info.setEseId(dealerAcct.getEnterpriseId());
			info.setPhoneNumber(dealerAcct.getContact());
			info.setAcctType(dealerAcct.getAcctType());
			info.setDealerOrShopId(dealerAcct.getDealerId());
			info.setUserType(dealerAcct.getUserType());
			//企业信息
			info.setEseCode(enterprise.getCode());
			info.setEseName(enterprise.getName());
			info.setBasicModuleEseId(enterprise.getBasicModuleId());
			info.setDealersAcctPromotionCode(dealerAcct.getDealersAcctPromotionCode());
			
			return info;
	}
	
	/**
	 * LoginSession--转换-->ILoginResponse
	 * 
	 * @param session
	 * @return
	 */
	public ILoginResponse convert(LoginSession session) {
		AuthenticationInfo info = session.getInfo();
		if (info == null) {
			throw new MessageException("LoginSession对象中属性info没有正确的值。");
		}
		Integer acctId = info.getAcctId();
		if (acctId == null) {
			throw new MessageException("LoginSession对象中属性info没有正确的值。");
		}
		LoginData loginData = new LoginData();
		loginData.setEnterpriseCode(info.getEseCode());//企业code
		loginData.setUserDealerId(info.getDealerOrShopId());//经销商id
		loginData.setUserId(info.getAcctId());//经销商用户账号id
		loginData.setToken(session.getToken());
		String loginStr = JacksonUtil.write2JsonString(loginData);
		logger.info("登陆信息：{}",loginStr);
		return loginData;
	}
	
	@Override
	public String generateToken(AuthenticationInfo authenticationInfo) {
		return this.getToken(authenticationInfo.getEseCode(), String.valueOf(authenticationInfo.getAcctId()));
	}
	
	/**
	 *  返回token
	 *  
	 * @param eseCode
	 * @param userId
	 * @return
	 */
	private String getToken(String eseCode,String userId){
		return eseCode+"_"+userId;
	}
}
